﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Buy : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Title = "我的购物车";
        
        if (Session["user"] == null)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请登录后再购物');\nlocation.href='Default.aspx';", true);
        }

        else  if (!IsPostBack)
        {
           
            id.Text = Session["Id"]!=null?Session["Id"].ToString():"";
            Proname.Text = Session["Proname"]!=null?Session["Proname"].ToString():"";
            MemberPrice.Text = Session["MemberPrice"]!=null?Session["MemberPrice"].ToString():"";
            binder();
            btnClear.OnClientClick = "return window.confirm('确认清空购物车吗')";
            btnChk.OnClientClick = "return window.confirm('确认结账吗')";
        }
        
    }
    public void binder()//购物车数据绑定
    {

        if (Session["cart"] == null || Session["cart"].ToString() == "")
        {
            lblMsg.Text = "暂无商品";
            gdvList.Visible = false;
            lblSum.Text = "";

        }
        else
        {
            DataTable dt = (DataTable)Session["cart"];
            if (dt.Rows.Count == 0)
            {
                lblMsg.Text = "暂无商品";
                lblSum.Text = "";
                gdvList.Visible = false;
            }
            else
            {
                gdvList.Visible = true;
                this.gdvList.DataSource = dt.DefaultView;
                this.gdvList.DataBind();
                decimal sum = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sum += (int.Parse(dt.Rows[i]["ProNum"].ToString()) * decimal.Parse(dt.Rows[i]["MemberPrice"].ToString()));

                }
                lblSum.Text = sum.ToString();
                lblMsg.Text = "";
            }
        }
    }
    public DataTable cart()//创建购物车临时表
    {
        DataTable dt = new DataTable("cart");
        dt.Columns.Add("ProId", typeof(int));//产品编号
        dt.Columns.Add("ProName", typeof(string));//产品名称
        dt.Columns.Add("MemberPrice", typeof(string));//价格
        dt.Columns.Add("ProNum", typeof(int));//数量
        return dt;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ///判断数量
        DbAccess db = new DbAccess();
        string sql = "select ProNum from product where ProId=" + int.Parse(id.Text) + "";
        DataSet dsPro = db.GetDataSet(sql);
        if (int.Parse(num.Text) > int.Parse(dsPro.Tables[0].Rows[0][0].ToString()))
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('商品数量超出库存数量目前此商品剩余" + dsPro.Tables[0].Rows[0][0].ToString()+ "件')", true);
        else
        {

            //添加到购物车
            if (Session["cart"] == null)
            {
                DataTable dt = cart();
                DataRow dr = dt.NewRow();
                dr["ProId"] = int.Parse(id.Text);
                dr["ProName"] = Proname.Text;
                dr["MemberPrice"] = MemberPrice.Text;
                dr["ProNum"] = int.Parse(num.Text);
                dt.Rows.Add(dr);
                Session["cart"] = dt;
                binder();


            }
            else///购物车已经存在，查找并修改数量
            {
                bool find = false;
                DataTable dt = (DataTable)Session["cart"];
                int i;
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(id.Text) == int.Parse(dt.Rows[i]["ProId"].ToString()))
                    {
                        dt.Rows[i]["ProNum"] = int.Parse(dt.Rows[i]["ProNum"].ToString()) + int.Parse(num.Text);
                        find = true;
                        break;
                    }
                }
                if (!find)//如果没有此商品，添加新商品
                {
                    DataRow dr = dt.NewRow();
                    dr["ProId"] = int.Parse(id.Text);
                    dr["ProName"] = Proname.Text;
                    dr["MemberPrice"] = MemberPrice.Text;
                    dr["ProNum"] = int.Parse(num.Text);
                    dt.Rows.Add(dr);

                }
                Session["cart"] = dt;//添加完成后保存到session中
                binder();
            }
        }


    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        Session["cart"] = null;
        binder();
    }
    protected void gdvList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ProId = int.Parse(this.gdvList.Rows[e.RowIndex].Cells[0].Text.ToString());
        DataTable dr = (DataTable)Session["cart"];
        for (int i = 0; i < dr.Rows.Count; i++)
        {
            if (ProId== int.Parse(dr.Rows[i]["ProId"].ToString()))
            {
                dr.Rows.RemoveAt(i);
                binder();
            }
        }
    }
    protected void btnChk_Click(object sender, EventArgs e)
    {
        
        if (Session["cart"] == null)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('还没有买东西呢');\nlocation.href='Default.aspx';",true);

        }
        else
        {
            

            DataTable dr = (DataTable)Session["cart"];
            DbAccess db = new DbAccess();
            string guid = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string user = Session["user"].ToString();
            //判断帐户余额是否充足
            DataSet dsAccount = db.GetDataSet("select account from userinfo where uid='" + user + "'");
            if (lblSum.Text == string.Empty || decimal.Parse(lblSum.Text) > decimal.Parse(dsAccount.Tables[0].Rows[0][0].ToString()))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('帐户余额不足');\nlocation.href='Account.aspx';", true);


            }
            else
            {
                ///添加结账时间,用户信息
                string sql = "insert into UserOrder values('" + guid + "','" + user + "','" + DateTime.Now.ToString() + "')";
                if (db.ExecuteSql(sql))
                {

                    if (db.DtbAdd(dr, guid, user))
                    {
                        Session.Remove("cart");
                        Session["cart"] = null;
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('结账成功');\nlocation.href='MyCartList.aspx';", true);
                    }
                    else
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('结账失败');\nlocation.href='Default.aspx';", true);



                }
               ////修改帐户余额
                decimal account = (decimal.Parse(dsAccount.Tables[0].Rows[0][0].ToString()) - decimal.Parse(lblSum.Text));
                 sql = "update userInfo set account=" +account.ToString() + " where uid='" + user + "'";
                db.ExecuteSql(sql);
            }

        }
    }
    protected void btnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
}
